package scfw.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 7sh on 2017/3/10.
 */
public class ZcjbSSOLogoutFilter implements Filter {

    /**
     * Logger instance
     */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final String TYPE_LOGOUT = "logout";
    private String casServerUrlPrefix = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info(">>>>>>进入 ZcjbSSOLogoutFilter init 方法");
        this.casServerUrlPrefix = filterConfig.getInitParameter("casServerUrlPrefix");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info(">>>>>>进入 ZcjbSSOLogoutFilter doFilter 方法");
        String type = servletRequest.getParameter("type");
        logger.info("type == >" + type);
        //如果进入退出页面的参数中带有type=logout，则执行退出后跳转至SSO的退出
        if (TYPE_LOGOUT.equals(type)) {
            logger.info(">>>>>执行退出操作，并跳转至SSO服务器的退出");

            //这里写退出逻辑
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            request.getSession().removeAttribute("user");

            HttpServletResponse response = (HttpServletResponse)servletResponse;
            //重定向SSO
            if(servletResponse instanceof HttpServletResponse){
                response.sendRedirect(casServerUrlPrefix+"/logout");
            }
        } else {
            //继续走，进入登录页面
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        logger.info(">>>>>>进入 ZcjbSSOLogoutFilter destroy 方法");
    }
}
